﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SASystem.SAServiceRef;

namespace SASystem
{
    public partial class MainFrm : Form
    {
        private bool m_isConnected;
        private int m_CheckPower=0;
        private string m_userName ="";
        public MainFrm()
        {
            InitializeComponent();
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            try
            {
                LogOutFinished();
                //ToolStripMenuItem_login_Click(null, null);
            }
            catch (System.Exception ex)
            {
                SABLL.ShowErrMsg(ex.Message);
            }
            //
        }

        private void ToolStripMenuItem_login_Click(object sender, EventArgs e)
        {
            //StartLogin(SABLL.GetRemoteServer());
            LoginFrm lf = new LoginFrm();
            lf.ShowDialog();
            
            if (lf.Success())
            {
                m_CheckPower = lf.CheckPower();
                m_userName = lf.UserName();
                LogInFinished();
            }
            else
            {
                LogOutFinished();
            }
        }

        private void DoRefreshCategoryView()
        {
            try
            {
                //update categories.
                SABLL.InitCategoryTreeView(this.treeView_Category);
                DoRefreshFamilyListView();
            }
            catch (System.Exception ex)
            {
                SABLL.ShowErrMsg(ex.Message);
            }
        }

        private void DoRefreshVendorView()
        {
            try
            {
                //update categories.
                SABLL.InitVendorTreeView(this.treeView_Vendor);
                DoRefreshFamilyListView();
            }
            catch (System.Exception ex)
            {
                SABLL.ShowErrMsg(ex.Message);
            }
        }

        private void DoRefreshFamilyListView()
        {
            TreeNode node = this.treeView_Category.SelectedNode;

            if (node == null) return;

            CategoryInfo curCateInfo = node.Tag as CategoryInfo;
            List<FamilyInfo> families = SABLL.GetFamiliesByCategoryId(curCateInfo.Id);

            SABLL.InitFamilyListView(this.listView_Families, families);
        }

        private void treeView_Category_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
               CategoryInfo curCateInfo = e.Node.Tag as CategoryInfo;
               List<FamilyInfo> families = SABLL.GetFamiliesByCategoryId(curCateInfo.Id);

               SABLL.InitFamilyListView(this.listView_Families, families);

            }
        }

        private void button_Search_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                string searchString = this.textBox_Search.Text;
                if (String.IsNullOrEmpty(searchString))
                {
                    return;
                }

                List<FamilyInfo> families = SABLL.SearchFamilies(searchString);

                if (families == null)
                {
                    SABLL.DoAlert();
                    return;
                }

                SABLL.InitFamilyListView(this.listView_Families, families);
            }
            catch (System.Exception ex)
            {
                SABLL.ShowInfoMsg(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void textBox_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button_Search_Click(null, null);
            }
        }

        private void ToolStripMenuItem_familyDownload_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = SABLL.GetSelectedListItem(this.listView_Families);

            if (selectedItem == null)
            {
                SABLL.ShowInfoMsg(@"无法下载，请在零件列表中至少选中一个零件！");
                return;
            }

            FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;

            if (selectedFamilyInfo != null)
            {
                this.Visible = false;
                FamilyDownFrm fdf = new FamilyDownFrm(selectedFamilyInfo);   
                fdf.ShowDialog();
                this.Visible = true;
            }
        }

        private void ToolStripMenuItem_familyDetail_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = SABLL.GetSelectedListItem(this.listView_Families);

            if (selectedItem == null)
            {
                SABLL.ShowInfoMsg(@"无法查看，请在零件列表中至少选中一个零件！");
                return;
            }

            FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;

            FamilyDetailFrm fdf = new FamilyDetailFrm(selectedFamilyInfo);
            fdf.ShowDialog();
        }

        private void ToolStripMenuItem_familyEdit_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = SABLL.GetSelectedListItem(this.listView_Families);

            if (selectedItem == null)
            {
                SABLL.ShowInfoMsg(@"无法编辑，请在零件列表中至少选中一个零件！");
                return;
            }

            FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;
            FamilyEditFrm fef = new FamilyEditFrm(selectedFamilyInfo);

            fef.ShowDialog();
        }

        private void ToolStripMenuItem_familyDelete_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = SABLL.GetSelectedListItem(this.listView_Families);

            if (selectedItem == null)
            {
                SABLL.ShowInfoMsg(@"无法删除，请在零件列表中至少选中一个零件！");
                return;
            }

            FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;

            if (selectedFamilyInfo != null)
            {
                if (SABLL.ShowConfirmMsg(String.Format("确认删除零件[{0}]？", selectedFamilyInfo.Name)) == DialogResult.Yes)
                {
                    if (SABLL.DeleteFamily(selectedFamilyInfo.ID))
                    {
                        SABLL.ShowInfoMsg(String.Format("删除{0}成功！", selectedFamilyInfo.Name));
                    }
                    else
                    {
                        SABLL.ShowInfoMsg(String.Format("删除{0}出错：{1}", selectedFamilyInfo.Name, SABLL.GetLastErrMsg()));
                    }
                    this.DoRefreshFamilyListView();
                }
            }
        }

        private void ToolStripMenuItem_familyAttrsDown_Click(object sender, EventArgs e)
        {
            ListViewItem selectedItem = SABLL.GetSelectedListItem(this.listView_Families);

            if (selectedItem == null)
            {
                SABLL.ShowInfoMsg(@"无法下载，请在零件列表中至少选中一个零件！");
                return;
            }

            FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;

            if (selectedFamilyInfo == null) return;

            FamilyAttrInfo familyAttrInfo = SABLL.GetFamilyAttrInfoByType(selectedFamilyInfo.ID,
            FamilyAttrType.kReference);

            if (familyAttrInfo != null && !String.IsNullOrEmpty(familyAttrInfo.ReferenceName) &&
                familyAttrInfo.ReferenceBinary != null && familyAttrInfo.ReferenceBinary.Length > 0)
            {
                string path = SABLL.SaveFileBrowser(FileType.kDocument, familyAttrInfo.ReferenceName);

                if (!String.IsNullOrEmpty(path))
                {
                    string referencePath = SABLL.SaveBinaryByPath(path, familyAttrInfo.ReferenceBinary);

                    SABLL.ShowInfoMsg(String.Format("保存文档成功！保存位置：{0}", path));
                }
            }
            else
            {
                //no referece document.
                SABLL.ShowInfoMsg(@"无可下载的文档资料！");
            }

            /*
            string folder = SABLL.OpenFolderBrowser();

            if (System.IO.Directory.Exists(folder))
            {
                FamilyInfo selectedFamilyInfo = selectedItem.Tag as FamilyInfo;
                FamilyAttrInfo familyAttr = SABLL.GetFamilyAttrInfo(selectedFamilyInfo.ID);

                string templateFilePath, modelPicPath, drawPicPath, drawingPath, referencePath;
                templateFilePath = System.IO.Path.Combine(folder, familyAttr.TemplateFileName);
                modelPicPath = System.IO.Path.Combine(folder, familyAttr.ModelPicName);
                drawPicPath = System.IO.Path.Combine(folder, familyAttr.DrawPicName);
                drawingPath = System.IO.Path.Combine(folder, familyAttr.DrawingName);
                referencePath = System.IO.Path.Combine(folder, familyAttr.ReferenceName);

                templateFilePath = SABLL.SaveBinaryByPath(templateFilePath, familyAttr.TemplateFileBinary);
                modelPicPath = SABLL.SaveBinaryByPath(modelPicPath, familyAttr.ModelPicBinary);
                drawPicPath = SABLL.SaveBinaryByPath(drawPicPath, familyAttr.DrawPicBinary);
                referencePath = SABLL.SaveBinaryByPath(referencePath, familyAttr.ReferenceBinary);
                drawingPath = SABLL.SaveBinaryByPath(drawingPath, familyAttr.DrawingBinary);

                SABLL.ShowInfoMsg(String.Format("保存附件成功！保存位置：{0}", folder));
            }
             */

        }

        private void ToolStripMenuItem_logout_Click(object sender, EventArgs e)
        {
            LogOutFinished();
        }

        private void StartLogin(string server)
        {
            //this.Text = @String.Format("零部件模型库客户端【正在连接中...服务器：{0}】", SABLL.GetRemoteServer());
        }

        private void LogInFinished()
        {
            try
            {
                if (this.tabControl_CateVendor.SelectedIndex == 0)
                {
                    //load data.
                    SABLL.InitCategoryTreeView(this.treeView_Category);
                }
                else
                {
                    SABLL.InitVendorTreeView(this.treeView_Vendor);
                }
            }
            catch (System.Exception ex)
            {
                SABLL.ShowErrMsg(ex.Message);
                LogOutFinished();
                return;
            }

            this.ToolStripMenuItem_Cmds.Enabled = true;
            this.contextMenuStrip_familyList.Enabled = true;
            this.button_Search.Enabled = true;
            this.textBox_Search.Enabled = true;

            //tool bar
            this.toolStripButton_familyEdit.Enabled = m_CheckPower==1?true:false;
            this.toolStripButton_cateEdit.Enabled = m_CheckPower == 1 ? true : false;
            this.toolStripButton_detail.Enabled = true;
            this.toolStripButton_downloadDoc.Enabled = true;
            this.toolStripButton_downloadFamily.Enabled = true;
            this.toolStripButton_familyDelete.Enabled = m_CheckPower == 1 ? true : false;
            this.toolStripButton_logout.Enabled = true;
            this.toolStripButton_publish.Enabled = m_CheckPower == 1 ? true : false;
            this.toolStripButton_standardEdit.Enabled = m_CheckPower == 1 ? true : false;
            this.toolStripButton_vendorEdit.Enabled = m_CheckPower == 1 ? true : false;

            //menu bar
            this.ToolStripMenuItem_CmdEditFamily.Enabled = m_CheckPower == 1 ? true : false;
            this.ToolStripMenuItem_CmdEditCategory.Enabled = m_CheckPower == 1 ? true : false;
            this.ToolStripMenuItem_familyDetail.Enabled = true;
            this.ToolStripMenuItem_CmdDocDown.Enabled = true;
            this.ToolStripMenuItem_CmdFamilyDown.Enabled = true;
            this.ToolStripMenuItem_CmdFamilyDelete.Enabled = m_CheckPower == 1 ? true : false;
            this.ToolStripMenuItem_logout.Enabled = true;
            this.ToolStripMenuItem_CmdFamilyPublish.Enabled = m_CheckPower == 1 ? true : false;
            this.toolStripMenuItem_CmdEditStandard.Enabled = m_CheckPower == 1 ? true : false;
            this.ToolStripMenuItem_CmdEditVender.Enabled = m_CheckPower == 1 ? true : false;
            this.ToolStripMenuItem_familyDelete.Enabled = m_CheckPower == 1 ? true : false;//右键菜单栏修改‘删除’修改
            this.ToolStripMenuItem_familyEdit.Enabled = m_CheckPower == 1 ? true : false;//右键菜单栏修改‘编辑’修改


            this.Text = @String.Format("零部件模型库客户端【{0}】登録中", m_userName);
            //this.Text = @String.Format("零部件模型库客户端【已连接到服务器---{0}】", SABLL.GetRemoteServer());
            
        }

        private void LogOutFinished()
        {
            //load data.
            this.treeView_Category.Nodes.Clear();
            this.treeView_Vendor.Nodes.Clear();
            this.ToolStripMenuItem_Cmds.Enabled = false;
            this.contextMenuStrip_familyList.Enabled = false;
            this.button_Search.Enabled = false;
            this.textBox_Search.Enabled = false;
            this.listView_Families.Clear();

            //tool bar
            this.toolStripButton_familyEdit.Enabled = false;
            this.toolStripButton_cateEdit.Enabled = false;
            this.toolStripButton_detail.Enabled = false;
            this.toolStripButton_downloadDoc.Enabled = false;
            this.toolStripButton_downloadFamily.Enabled = false;
            this.toolStripButton_familyDelete.Enabled = false;
            this.toolStripButton_logout.Enabled = false;
            this.toolStripButton_publish.Enabled = false;
            this.toolStripButton_standardEdit.Enabled = false;
            this.toolStripButton_vendorEdit.Enabled = false;

            //menu bar
            this.ToolStripMenuItem_familyEdit.Enabled = false;
            this.ToolStripMenuItem_CmdEditCategory.Enabled = false;
            this.ToolStripMenuItem_familyDetail.Enabled = false;
            this.ToolStripMenuItem_CmdDocDown.Enabled = false;
            this.ToolStripMenuItem_CmdFamilyDown.Enabled = false;
            this.ToolStripMenuItem_CmdFamilyDelete.Enabled = false;
            this.ToolStripMenuItem_logout.Enabled = false;
            this.ToolStripMenuItem_CmdFamilyPublish.Enabled = false;
            this.toolStripMenuItem_CmdEditStandard.Enabled = false;
            this.ToolStripMenuItem_CmdEditVender.Enabled = false;

            this.Text = @"零部件模型库【无连接】";
        }

        private void ToolStripMenuItem_About_Click(object sender, EventArgs e)
        {
            AboutFrm frm = new AboutFrm();
            frm.ShowDialog();
        }

        private void ToolStripMenuItem_CmdCacheMgr_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请在服务器端使用缓存功能！");
            //CacheMgrFrm cmf = new CacheMgrFrm();
            //cmf.ShowDialog();
        }

        private void ToolStripMenuItem_CmdFamilyPublish_Click(object sender, EventArgs e)
        {
            FamilyPubFrm fpf = new FamilyPubFrm();
            fpf.ShowDialog();
        }

        private void ToolStripMenuItem_CmdFamilyDetail_Click(object sender, EventArgs e)
        {
            this.ToolStripMenuItem_familyDetail_Click(sender, e);
        }

        private void ToolStripMenuItem_CmdEditCategory_Click(object sender, EventArgs e)
        {
            EditCategoryFrm fdf = new EditCategoryFrm();
            fdf.ShowDialog();

            this.DoRefreshCategoryView();
        }

        private void ToolStripMenuItem_CmdEditVender_Click(object sender, EventArgs e)
        {
            EditVenderFrm evf = new EditVenderFrm();
            evf.ShowDialog();
        }

        private void ToolStripMenuItem_CmdEditFamily_Click(object sender, EventArgs e)
        {
            this.ToolStripMenuItem_familyEdit_Click(sender, e);
        }

        private void ToolStripMenuItem_CmdFamilyDown_Click(object sender, EventArgs e)
        {
            this.ToolStripMenuItem_familyDownload_Click(sender, e);
        }

        private void ToolStripMenuItem_CmdDocDown_Click(object sender, EventArgs e)
        {
            this.ToolStripMenuItem_familyAttrsDown_Click(sender, e);
        }

        private void ToolStripMenuItem_CmdFamilyDelete_Click(object sender, EventArgs e)
        {
            this.ToolStripMenuItem_familyDelete_Click(sender, e);
        }

        private void ToolStripMenuItem_Conn_Click(object sender, EventArgs e)
        {

        }

        private void treeView_Vendor_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                VendorInfo curVendorInfo = e.Node.Tag as VendorInfo;
                List<FamilyInfo> families = new List<FamilyInfo>();

                if (curVendorInfo != null)
                {
                    families = SABLL.GetFamiliesByVendorId(curVendorInfo.VendorId);
                }
                else
                {
                    CategoryVendorHelpInfo cvInfo = e.Node.Tag as CategoryVendorHelpInfo;
                    if (cvInfo != null)
                    {
                        families = SABLL.GetFamiliesByCategoryVendorId(new Guid(cvInfo.cateID), cvInfo.vendorID);
                    }
                }

                SABLL.InitFamilyListView(this.listView_Families, families);
            }
        }

        private void tabControl_CateVendor_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if not login, return.

            if (!this.ToolStripMenuItem_Cmds.Enabled)
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            try
            {
                TabControl tablCtl = (TabControl)sender;
                if (tablCtl.SelectedIndex == 0)
                {
                    this.DoRefreshCategoryView();
                }
                else
                {
                    this.DoRefreshVendorView();
                }
            }
            catch (Exception ex)
            {
                SABLL.ShowErrMsg(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripMenuItem_CmdEditStandard_Click(object sender, EventArgs e)
        {
            EditStandardFrm esf = new EditStandardFrm();
            esf.ShowDialog();
        }

        private void toolStripButton_login_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_login_Click(sender, e);
        }

        private void toolStripButton_logout_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_logout_Click(sender, e);
        }

        private void toolStripButton_detail_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_familyDetail_Click(sender, e);
        }

        private void toolStripButton_downloadFamily_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdFamilyDown_Click(sender, e);
        }

        private void toolStripButton_downloadDoc_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdDocDown_Click(sender, e);
        }

        private void toolStripButton_familyDelete_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdFamilyDelete_Click(sender, e);
        }

        private void toolStripButton_publish_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdFamilyPublish_Click(sender, e);
        }

        private void toolStripButton_cateEdit_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdEditCategory_Click(sender, e);
        }

        private void toolStripButton_vendorEdit_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdEditVender_Click(sender, e);
        }

        private void toolStripButton_standardEdit_Click(object sender, EventArgs e)
        {
            toolStripMenuItem_CmdEditStandard_Click(sender, e);
        }

        private void toolStripButton_familyEdit_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_CmdEditFamily_Click(sender, e);
        }

        private void toolStripButton_help_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_About_Click(sender, e);
        }
    }
}
